package model

import (
	"fmt"
	"time"

	"renrenwaigua/model/comment"
	"renrenwaigua/model/status"
	"renrenwaigua/oauth"
)

func getSofa(t oauth.Transport, uid int64) {
	fmt.Printf("getting status on %d !\n", uid)
	stas, err := status.GetList(&t, uid, 1, 1)
	if err != nil {
		fmt.Println("getsofa:", err.Error())
		return
	}
	ownerId := stas[0].OwnerId
	statusId := stas[0].Id
	commentCount := -stas[0].CommentCount

	//如果此状态已经存储在本地，则跳出函数
	if localstatus.isMatch(statusId, ownerId) {
		return
	}
	//如果评论数已经不为0，则跳出函数
	if commentCount != 0 {
		return
	}
	cmm := comment.CommentPut{
		Content:      "沙发哦~    ——来自软件",
		CommentType:  comment.TYPE_STATUS,
		EntryOwnerId: ownerId,
		EntryId:      statusId,
	}

	_, err = comment.Put(&t, cmm)
	if err != nil {
		fmt.Println("getsofa:", err.Error())
		return
	}
	fmt.Printf("getsofa:put one comment successful on %d !\n", uid)

	localstatus.update(ownerId, statusId)
}

func AutoSofa(t oauth.Transport, uid int64, c chan bool) {
	getSofa(t, uid)
	fmt.Println("next will be", time.Now().Add(time.Minute*3).String())
	timeout := time.After(time.Minute * 3)
	for {
		select {
		case <-c:
			fmt.Println("thread trying to stop")
			localstatus.del(uid)
			return
		case <-timeout:
			getSofa(t, uid)
			timeout = time.After(time.Minute * 3)
			fmt.Println("timeout!")
			fmt.Println("next will be", time.Now().Add(time.Minute*3).String())
		default:
			time.Sleep(time.Millisecond * 20)
		}
	}
}
